package com.hcinfos.gsoo.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.util.IntentUtil;
import com.hcinfos.gsoo.util.LogUtil;

/**
 * tab
 * 
 * @author john
 * 
 */
public class RegActivity extends Activity implements OnClickListener {

	private TextView register_tv;
	private ImageView back_iv;
	private Animation shake;

	private EditText userName_et;
	private EditText userPass_et;
	private Button reg_bt;

	private TextView msg_tv;
	private ProgressBar bar;
	private Dialog dialog;

	private final int REG_SUUCESS = 0x1120;
	private final int REG_FAIL = REG_SUUCESS + 1;
	private final int SUCCESS_DIALOG_DISMISS = REG_SUUCESS + 2;
	private final int FAIL_DIALOG_DISMISS = REG_SUUCESS + 3;

	private Context context;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reg);
		int width = getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		context = this;
		initRes();
	}

	private void initRes() {

		register_tv = (TextView) findViewById(R.id.register_tv);
		register_tv.setOnClickListener(this);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);

		userName_et = (EditText) findViewById(R.id.userName_et);
		userPass_et = (EditText) findViewById(R.id.userPass_et);
		reg_bt = (Button) findViewById(R.id.reg_bt);
		reg_bt.setOnClickListener(this);

		LayoutInflater inflater = getLayoutInflater();
		RelativeLayout dialog_rl = (RelativeLayout) inflater.inflate(
				R.layout.progress_wait_view, null);
		msg_tv = (TextView) dialog_rl.findViewById(R.id.RequestLoadingText);
		bar = (ProgressBar) dialog_rl.findViewById(R.id.requestLoadingProgress);
		msg_tv.setText("注册中..");

		dialog = new Dialog(this, R.style.QuitDialog);
		dialog.setContentView(dialog_rl);
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = (int) (280 * Common.PROPORTION); // 宽度
		lp.height = (int) (180 * Common.PROPORTION); // 高度
		dialogWindow.setAttributes(lp);
	}

	private Intent intent;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.register_tv:
			intent = new Intent(this, AgreeActivity.class);
			startActivity(intent);
			break;
		case R.id.back_iv:
			intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
			finish();
			break;
		case R.id.reg_bt:
			if (regCheck()) {
				dialog.show();
				reg();
			}
			break;
		}
	}

	private void reg() {
		final String username = userName_et.getText().toString();
		final String password = userPass_et.getText().toString();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							context, Urls.USER_REG + "&user.email=" + username
									+ "&user.password=" + password);
					LogUtil.d("wxf", "result:" + result);
					JSONObject obj = new JSONObject(result);
					int state = -1;
					String number = null;
					if (!obj.isNull("state")) {
						state = obj.getInt("state");
					}
					if (!obj.isNull("data")) {
						number = obj.getJSONObject("data")
								.getString("ggnumber");
					}
					String message = obj.getString("message");
					if (state == 200) {
						Message msg = handler.obtainMessage();
						msg.what = REG_SUUCESS;
						msg.obj = number;
						handler.sendMessage(msg);
					} else {
						Message msg = handler.obtainMessage();
						msg.what = REG_FAIL;
						msg.obj = message;
						handler.sendMessage(msg);
					}

				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = REG_FAIL;
					handler.sendMessage(msg);
					LogUtil.e("wxf", "gsooReg=" + e.toString());
				}

			}
		}).start();
	}

	String gNumber = null;
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			bar.setVisibility(View.GONE);
			switch (msg.what) {
			case REG_SUUCESS:
				if (msg.obj != null) {
					gNumber = (String) msg.obj;
					msg_tv.setText("Gsoo号:" + gNumber);
				} else {
					msg_tv.setText("抱歉,注册失败");
				}
				handler.sendEmptyMessageDelayed(SUCCESS_DIALOG_DISMISS, 3000);
				break;
			case REG_FAIL:
				if (dialog != null)
					dialog.dismiss();
				handler.sendEmptyMessageDelayed(FAIL_DIALOG_DISMISS, 3000);
				String error = "注册失败!";
				if (msg.obj != null) {
					error = msg.obj.toString();
				}
				Toast.makeText(RegActivity.this, error, 500).show();
				break;
			case SUCCESS_DIALOG_DISMISS:
				if (dialog != null)
					dialog.dismiss();
				IntentUtil.start_activity(RegActivity.this,
						LoginActivity.class, new BasicNameValuePair("email",
								gNumber), new BasicNameValuePair("password",
								userPass_et.getText().toString()));
				finish();
				break;
			case FAIL_DIALOG_DISMISS:
				if (dialog != null)
					dialog.dismiss();
				break;
			}
		};
	};

	private boolean regCheck() {
		String username = userName_et.getText().toString();
		String password = userPass_et.getText().toString();
		if (username.length() == 0) {
			Toast.makeText(this, "邮箱号不能为空", 500).show();
			userName_et.startAnimation(shake);
			return false;
		}
		if (!getEmail(username)) {
			Toast.makeText(this, "邮箱号格式不对!", 500).show();
			userName_et.startAnimation(shake);
			return false;
		}
		if (password.length() < 6) {
			Toast.makeText(this, "密码长度必须为5位以上", 500).show();
			userPass_et.startAnimation(shake);
			return false;
		}
		return true;
	}

	private boolean getEmail(String line) {
		Pattern p = Pattern
				.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		Matcher m = p.matcher(line);
		return m.find();
	}
}
